<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Gzip文件压缩与解压</title>
</head>
<body>
<div>
    <strong>压缩文件到gz: </strong>
    <input type="file" id="fileToGz">
</div>
<div>
    <strong>解压gz到文件: </strong>
    <input type="file" id="gzToFile" accept=".gz">
</div>

<script src="pako.min.js"></script>
<!--如果需要支持那些不自带atob btoa的浏览器，就需要用下面这个包来进行base64-->
<!--<script src="https://cdn.staticfile.org/Base64/1.0.2/base64.min.js"></script>-->
<script>
    
document.getElementById('fileToGz').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const binaryString = pako.gzip(e.target.result, {to: 'string'})
            const blob = new Blob([binaryString], { type: 'application/gzip' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = file.name + '.gz';
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
        };
        reader.readAsText(file);
    }
});
    
document.getElementById('gzToFile').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const binaryString = e.target.result;
            const charArray = binaryString.split('').map(char => char.charCodeAt(0));
            const byteArray = new Uint8Array(charArray);
            const decompressedText = pako.ungzip(byteArray, { to: 'string' });

            const blob = new Blob([decompressedText], { type: 'text/plain' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            var name = file.name.endsWith('.gz') ? file.name.slice(0, -3) : file.name;
            name = name.lastIndexOf('.') === -1 ? name + ".txt" : name;
            a.download = name;
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
        };
        reader.readAsText(file);
    }
});
</script>
</body>
</html>